import 'dart:async';

import 'package:get/get.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';

class ChangeVerificationCodeController extends GetxController {
  /// 响应式成员变量
  final _secondsRemaining = 60.obs;

  set secondsRemaining(value) => _secondsRemaining.value = value;

  get secondsRemaining => _secondsRemaining.value;

  final arguments = <String, dynamic>{}.obs;

  /// 成员变量
  late Timer? _timer;

  /// 事件
  Future<void> sendVerificationCode() async {
    if (secondsRemaining != 0) {
      toast('Resend after $secondsRemaining seconds');
      return;
    }
    Loading.show();
    await Request()
        .post(
      '/userConfig/sendCode',
      {
        'email': arguments['email'],
        'mobile': arguments['mobile'],
        'mobileType': arguments['mobileType'],
        'sendType': 3,
      }..removeWhere((key, value) => value == null),
    )
        .then((_) {
      startCountdown();
    });
  }

  Future<void> updateMobileOrEmail(String code) async {
    Loading.show();
    await Request()
        .post(
      '/user/updateMobileOrEmail',
      {
        'type': arguments['type'],
        'newEmail': arguments['email'],
        'newMobile': arguments['mobile'],
        'mobileType': arguments['mobileType'],
        'validateCode': code,
      }..removeWhere((key, value) => value == null),
    )
        .then((result) {
      UserStore.to.saveProfile(UserLoginResponseEntity.fromJson(result['result']));
      Get.offAndToNamed(Routes.ACCOUNTINFOCHANGERESULT, arguments: Get.arguments);
    });
  }

  void startCountdown() {
    secondsRemaining = 60;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (secondsRemaining > 0) {
        secondsRemaining--;
      } else {
        timer.cancel();
      }
    });
  }

  void stopCountdown() {
    _timer?.cancel();
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
    arguments.value = Get.arguments;
  }

  @override
  void onReady() {
    super.onReady();
    startCountdown();
  }

  @override
  void dispose() {
    super.dispose();
    stopCountdown();
  }
}
